package cn.edu.seu.herald.informationplatform.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import cn.edu.seu.herald.informationplatform.bean.league.Activity;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueInfo;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueUser;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.SessionIdNotFound;
import cn.edu.seu.herald.informationplatform.dao.database.ActivityDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;
import cn.edu.seu.herald.informationplatform.util.filetools.PicTools;

public class ActivityAdd extends HttpServlet {

	private static final boolean SUCCESS = true;

	private static final boolean FAILURE = false;

	private static final String SUCCESS_MESSAGE = "操作成功";

	private static final String FAILURE_MESSAGE = "操作失败";

	private Object newimage;
	
	public Activity addDefaultPic(Activity activity,int id){
		try{
			String path = getServletContext().getRealPath("/");
			LeagueUserDao leagueUserDao = LeagueUserDao.getDao();
			LeagueUser leagueUser = leagueUserDao.getLeagueUser(id);
			
			LeagueInfoDao leagueInfoDao = LeagueInfoDao.getDao();
			LeagueInfo leagueInfo = leagueInfoDao.getLeagueInfo(leagueUser.getLeagueInfoId());
			String portrait = leagueInfo.getPortrait();
            
			File saveFile = null;//原头像存放处
			String saveFilePathString = null;
			String destSaveFilePathString = null;
			Properties pro = System.getProperties();
	        String osName = pro.getProperty("os.name");
		     if("linux".equalsIgnoreCase(osName)){
		    	 saveFilePathString = path+portrait;
		    	 destSaveFilePathString = path+"/postPictures/"+portrait.replaceAll("/","_");
		     }else{
		    	 saveFilePathString = path+portrait.replaceAll("/","\\\\");
		    	 destSaveFilePathString = path+"postPictures\\"+portrait.replaceAll("/","_");
		     }
		     String defPortrait = null;
		     defPortrait = "postPictures/" + portrait.replaceAll("/","_");
			saveFile = new File(saveFilePathString);
			PicTools.copy(saveFilePathString,destSaveFilePathString);
            
			 
			activity.setPicWallAddress(defPortrait);//写大图
			
			
			
			Image src = ImageIO.read(saveFile);             
			double old_w=src.getWidth(null);                                     
			double old_h=src.getHeight(null);   
			double new_w=0;
			double new_h=0;
			double w_standard=380;
			double h_standard=212;
			double w_h_rate = old_w/old_h;
			double w_h_rate_standard = w_standard/h_standard;
			
			double tempdouble; 
			if(w_h_rate>w_h_rate_standard){
			tempdouble=old_w/w_standard;
			}else{
			tempdouble=old_h/h_standard;
			}
			new_w=Math.round(old_w/tempdouble);
			new_h=Math.round(old_h/tempdouble);//计算新图长宽
			BufferedImage tag = new BufferedImage((int)new_w,(int)new_h,BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src,0,0,(int)new_w,(int)new_h,null); 
			
			Random generator = new Random();
			int r = Math.abs(generator.nextInt());
			String fileName = r+".jpg";
			String relativeSavePathMin = "minPostPictures/"+fileName;
			String savePathMin = path+fileName;//输出绝对地址
			 if("linux".equalsIgnoreCase(osName)){
				 savePathMin = path+"/minPostPictures/"+fileName;  
		     }else{
		    	 savePathMin=path+"minPostPictures\\"+fileName;
		     }
			
			FileOutputStream newimage=new FileOutputStream(savePathMin);          //输出到文件流
			activity.setPostAddress(relativeSavePathMin);//写小图
			System.out.println("小图相对："+relativeSavePathMin);
			System.out.println("小图绝对："+savePathMin);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);       
			encoder.encode(tag);                                               //近JPEG编码
			newimage.close();
			return activity;
			}catch (Exception e) {
				e.printStackTrace();
				return null;
			}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		try {
			ActivityDao activityAccess = ActivityDao.getDao();
			
			String classId = request.getParameter("classId");
			String name = request.getParameter("name");
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			String information = request.getParameter("information"); 
			String contact = request.getParameter("contact");
			String organizer = request.getParameter("organizer");
			
			if (classId == null || name == null || startTime == null
					|| endTime == null || information == null || information == null
					|| contact == null || organizer == null) {
				printResult(response, FAILURE);
				return;
			}
			
			Activity activity = new Activity();
			activity.setClassId(Integer.valueOf(classId));
			activity.setName(name);
			activity.setStartTime(startTime);
			activity.setEndTime(endTime);
			activity.setInformation(information);
	        
			activity.setContact(contact);
			activity.setOrganizer(organizer);
			activity.setApplicantCount(0);
			activity.setReleaseTime(new java.sql.Date(
					new java.util.Date().getTime()));
			LeagueUserSessionCookieAccess lUserSessionCookieAccess = new LeagueUserSessionCookieAccess(request);
			int itLeagueId = lUserSessionCookieAccess.getLeagueId();			
			activity.setLeagueId(itLeagueId);
			addDefaultPic(activity, itLeagueId);
			System.out.println("post:"+activity.getPostAddress());
			activityAccess.addActivity(activity);
			
			
			LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			response.sendRedirect("./activities.jsp?league="+luSessionCookieAccess.getLeagueId());
		} catch (SQLException e) {
			printResult(response, FAILURE);
			return;
		} catch (NumberFormatException e) {
			printResult(response, FAILURE);
			return;
		} catch (SessionIdNotFound e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		printResult(response, SUCCESS);
	}
	
	private void printResult(HttpServletResponse response,
			boolean success) throws IOException {
		response.getWriter().println((success) ?
				SUCCESS_MESSAGE : FAILURE_MESSAGE);
	}

}
